#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Student
{
	//数据域：值域
	int iId;
	char caName[32];
	float fScore;
	//指针域
	struct Student *pNext;
}STU;

STU *mkSTUNode()
{
	STU *stu = (STU*)malloc(sizeof(STU));
	if (NULL == stu)
	{//空间申请失败
		//EXIT_FAILURE 1
	    //EXIT_SUCCESS 0
		exit(EXIT_FAILURE);
	}
	else
	{//malloc申请的空间不会自动把野值覆盖掉
	 //所以需要手动对申请的空间进行垃圾数据清理	
		memset(stu, 0, sizeof(STU));	
	}
	return stu;
}

void input(STU *stu)
{
	if (NULL != stu)
	{
		printf("请输入学生的信息id,name,score:\n");
		scanf("%d%s%f", &stu->iId, stu->caName
					  , &stu->fScore);
	}
}

void display(STU *head)
{
	if (NULL == head)
	{
		return;
	}
	
	STU *node = head->pNext;
	while (NULL != node)
	{
		printf("id:%d,name:%s,score:%.1f\n", node->iId
			   , node->caName, node->fScore);
		node = node->pNext;
	}
}
#if 0
//头插法
void insert(STU *head, STU *node)
{
	if (NULL == head || NULL == node)
	{
		return;
	}
	if (NULL == head->pNext)	
	{
		head->pNext = node;
	}
	else
	{
		node->pNext = head->pNext;
		head->pNext = node;
	}
}
#endif

//尾插法
void insert(STU *head, STU *node)
{
	if (NULL == head || NULL == node)
	{
		return;
	}

	if (NULL == head->pNext)
	{//空链表
		head->pNext = node;
	}
	else
	{
		STU *tmp = head->pNext;
		//循环遍历到最后一个节点
		while (NULL != tmp->pNext)
		{
			tmp = tmp->pNext;
		}
		//将新节点放在最后一个节点的后面
		tmp->pNext = node;
	}

}

void delById(STU *head, int id)
{
	if (NULL == head)
	{
		return;
	}
	STU *pre = head->pNext;
	STU *cur = pre;
	while (NULL != cur)
	{
		if (id == cur->iId)
		{
			if (cur == head->pNext)
			{//要删除的是第一个节点
				head->pNext = cur->pNext;
			}	
			else
			{//要删除的不是第一个节点
				pre->pNext = cur->pNext;
			}
			free(cur);
			cur = NULL;
			break;
		}
		pre = cur;
		cur = cur->pNext;
	}



}

int main(void)
{
	//将一个值域为空的节点作为链表的头
	STU *listHead = mkSTUNode();	

	int i=0;
	STU *node = NULL;
	for (; i<3; i++)
	{
		node = mkSTUNode();
		input(node);
		insert(listHead, node);
	}
	display(listHead);	

	printf("-------------------\n");	
	delById(listHead, 1001);
	display(listHead);
	
	printf("-------------------\n");	
	delById(listHead, 1002);
	display(listHead);

	return 0;
}



